import json
import os
import threading
from datetime import datetime, timedelta
import time
from block.monitor import Monitor, Congestion
from util import get_latest_folder, get_pass_time
from kafka import KafkaProducer


class ProcessEvent:
    def __init__(self, config_data, define):
        self.config_data = config_data
        self.format_str = self.config_data["format_str"]
        self.gantry_info = self.config_data["gantry_info"]
        self.define = define
        # 时间窗口
        # self.window_length = timedelta(minutes=float(self.gantry_info['time_interval']))
        self.window_length = None
        # 移动时间
        self.time_move = timedelta(minutes=float(self.gantry_info['time_move']))
        self.route_list = self.config_data["route"]
        # 门架数据
        self.gantry_data = {}
        # 实时时间
        self.current_simulated_time = None
        self.load_time = None
        self.diff_time = None
        # 时间窗口
        self.start_time = None
        self.end_time = None
        # 接收的最后一帧数据
        self.last_car = None
        # 事件分析
        self.monitor = Monitor(self.config_data["threshold"])
        # 拥堵分析
        self.congestion = Congestion(self.config_data["threshold"], self.define)
        # 线程管理
        self.thread_flag = True
        # 各车型期望通行时间表
        self.type_pass_time = {}
        # 各车型通行时间表
        self.type_pass_time_ture = {}
        # 保存事故数据地址
        self.save_json_path = None
        # 是否保存过程数据
        self.SAVE = True
        # 结束标志位
        self.flag = None

        self.kafka_producer = KafkaProducer(
            bootstrap_servers=self.config_data["kafka_host"],
            key_serializer=str.encode,
            value_serializer=lambda x: json.dumps(x).encode('utf-8')
        )

    def init(self):
        # current_up_list、current_down_list 存储当前时间区间内上下游车辆数量，保存为时间列表
        # up_data_dict、down_data_dict   存储上下游门架数据，保存到以车牌为键的字典
        # detention_dict    滞留车辆字典，暂时未用
        # interval_dict       存储当前时间区间内车辆信息
        # up_vlp_time_dict、down_vlp_time_dict    计算通行率时长字典
        self.gantry_data = {
            "current_up_list": [],
            "current_down_list": [],
            "up_data_dict": {},
            "down_data_dict": {},
            "detention_dict": {},
            "interval_dict": {},
            "up_vlp_time_dict": {},
            "down_vlp_time_dict": {},
            "in_num": 0,
            "out_num": 0
        }
        # 按指定速度计算合适的区间通行时间
        self.type_pass_time = get_pass_time(self.gantry_info["dist"])
        # 设置时间粒度
        # self.window_length = timedelta(minutes=float(self.type_pass_time["1"] * 0.5))
        self.window_length = timedelta(minutes=float(self.config_data["gantry_info"]["time_interval"]))

        folder_path = get_latest_folder(self.config_data["save_json_path"])
        self.save_json_path = os.path.join(folder_path, self.gantry_info["info"] + ".json")

    def add_message(self, q):
        '''
        更新新的门架数据
        '''
        while not q.empty():
            message = q.get(timeout=0.1)
            # print("收到消息:", message)
            current_time0 = message[self.define["TIME"]]
            self.current_simulated_time = datetime.strptime(current_time0, self.format_str)
            # 初始化时间
            if self.diff_time is None:
                self.load_time = datetime.now()
                self.diff_time = self.current_simulated_time - self.load_time
            if self.start_time is None:
                self.start_time = datetime.strptime(current_time0, self.format_str)
                self.end_time = self.start_time + self.window_length
            # 添加新的门架数据
            gantry_id = message[self.define["GANTRY"]]
            if gantry_id == self.gantry_info["up_gantry_id"]:
                current_time = datetime.strptime(message[self.define["TIME"]], self.format_str)
                vlp = message[self.define["PLATE"]]
                if vlp in self.gantry_data["up_data_dict"].keys():
                    # if current_time - self.gantry_data["up_data_dict"][vlp][self.define["TIME"]] <= timedelta(minutes=30):
                    continue
                # 添加新的上游门架过车的时间信息
                self.gantry_data["current_up_list"].append(current_time)
                # 添加新的上游门架过车信息
                self.gantry_data["up_data_dict"][vlp] = {self.define["TYPE"]: str(message[self.define["TYPE"]]),
                                                         self.define["TIME"]: current_time}
                self.gantry_data["interval_dict"][vlp] = {self.define["TYPE"]: str(message[self.define["TYPE"]]),
                                                          self.define["TIME"]: current_time}
                # 更新上游车辆数量
                self.gantry_data["in_num"] += 1
            elif gantry_id == self.gantry_info["down_gantry_id"]:
                current_time = datetime.strptime(message[self.define["TIME"]], self.format_str)
                vlp = message[self.define["PLATE"]]
                if vlp in self.gantry_data["down_data_dict"].keys():
                    continue
                # 添加新的下游门架过车的时间信息
                self.gantry_data["current_down_list"].append(current_time)
                # 添加新的下游门架过车信息
                self.gantry_data["down_data_dict"][vlp] = {self.define["TYPE"]: str(message[self.define["TYPE"]]),
                                                           self.define["TIME"]: current_time}
                self.gantry_data["down_vlp_time_dict"][vlp] = {self.define["TYPE"]: str(message[self.define["TYPE"]]),
                                                               self.define["TIME"]: current_time}
                # 更新下游车辆数量
                self.gantry_data["out_num"] += 1
                # 删除interval_dict中车辆经过下游的车辆信息
                if vlp in self.gantry_data["interval_dict"].keys():
                    del self.gantry_data["interval_dict"][vlp]

    def expire_clear(self, start_time, end_time, flag=True):
        # 清除过期数据(一小时前未匹配上的上游门架数据)
        # save_time = self.gantry_info["car_pass_time"] + self.config_data["time_move"]
        save_time = 60
        max_pass_time = 0
        if not flag:
            max_pass_time = self.type_pass_time["1"]
        else:
            for i in self.type_pass_time.keys():
                if self.type_pass_time[i] > max_pass_time:
                    max_pass_time = self.type_pass_time[i]
        pass_time = max_pass_time + self.gantry_info["time_move"]
        min_pass_time = max_pass_time * 0.5
        # 清除时间过期数据，只保留当前时间范围内的数据
        i = 0
        while i < len(self.gantry_data["current_up_list"]):
            if self.gantry_data["current_up_list"][i] < start_time:
                i += 1
            else:
                break
        self.gantry_data["current_up_list"] = self.gantry_data["current_up_list"][i:]
        j = 0
        while j < len(self.gantry_data["current_down_list"]):
            if self.gantry_data["current_down_list"][j] < start_time:
                j += 1
            else:
                break
        self.gantry_data["current_down_list"] = self.gantry_data["current_down_list"][j:]
        # print("过期数据:", i, j)
        # 删除过期save_time以上的上游门架数据
        del_up_vlp_list = []
        up_vlp_list = list(self.gantry_data["up_data_dict"].keys())
        for vlp in up_vlp_list:
            data_time = self.gantry_data["up_data_dict"][vlp][self.define["TIME"]]
            if data_time < end_time - timedelta(minutes=save_time):
                del_up_vlp_list.append(vlp)
        
        # 删除过期save_time以上的上游门架数据
        in_vlp_list = []
        self.gantry_data["up_vlp_time_dict"].clear()
        for vlp in up_vlp_list:
            data_time = self.gantry_data["up_data_dict"][vlp][self.define["TIME"]]
            if (start_time - timedelta(minutes=pass_time)) <= data_time < (end_time - timedelta(minutes=min_pass_time+self.gantry_info["time_move"])):
                in_vlp_list.append(vlp)
        for vlp in in_vlp_list:
            up_vlp = self.gantry_data["up_data_dict"][vlp]
            self.gantry_data["up_vlp_time_dict"][vlp] = {self.define["TIME"]: up_vlp[self.define["TIME"]],
                                                         self.define["TYPE"]: up_vlp[self.define["TYPE"]]}
        for vlp in del_up_vlp_list:
            del self.gantry_data["up_data_dict"][vlp]

        # 删除当前时间区间以外的下游门架数据
        del_down_vlp_list = []
        down_vlp_list = list(self.gantry_data["down_data_dict"].keys())
        for vlp in down_vlp_list:
            data_time = self.gantry_data["down_data_dict"][vlp][self.define["TIME"]]
            if data_time < start_time:
                del_down_vlp_list.append(vlp)
        for vlp in del_down_vlp_list:
            del self.gantry_data["down_data_dict"][vlp]
        # 删除当前时间区间以外的下游门架数据
        out_vlp_list = []
        out_down_vlp_list = list(self.gantry_data["down_vlp_time_dict"].keys())
        for vlp in out_down_vlp_list:
            data_time = self.gantry_data["down_vlp_time_dict"][vlp][self.define["TIME"]]
            if data_time < start_time - timedelta(minutes=pass_time) + timedelta(minutes=min_pass_time):
                out_vlp_list.append(vlp)
        for vlp in out_vlp_list:
            del self.gantry_data["down_vlp_time_dict"][vlp]

        # 删除当前时间区间以外的滞留车辆数据
        interval_vlp_list = []
        out_interval_vlp_list = list(self.gantry_data["interval_dict"].keys())
        for vlp in out_interval_vlp_list:
            data_time = self.gantry_data["interval_dict"][vlp][self.define["TIME"]]
            if data_time < end_time - timedelta(hours=24):
                interval_vlp_list.append(vlp)
        for vlp in interval_vlp_list:
            del self.gantry_data["interval_dict"][vlp]

    def type_analysis(self, flag=True):
        type_speed_dict = {}
        type_pass_rate_dict = {}
        last_type_pass_time_ture = self.type_pass_time_ture.copy()
        self.type_pass_time_ture = {}
        down_data_dict = self.gantry_data["down_data_dict"].copy()
        up_data_dict = self.gantry_data["up_data_dict"].copy()
        new_time = self.end_time - self.time_move - self.time_move
        # detention_dict = self.gantry_data["detention_dict"]
        # 根据下游过车信息匹配上游数据，计算车辆速度等信息
        vlp_list = list(down_data_dict.keys())
        for vlp in vlp_list:
            dist = None
            up_time = None
            down_time = down_data_dict[vlp][self.define["TIME"]]
            vehicle_type = down_data_dict[vlp][self.define["TYPE"]]
            # 查找上游门架对应车牌出现时间，计算平均速度
            if vlp in up_data_dict.keys():
                up_time = up_data_dict[vlp][self.define["TIME"]]
                dist = self.gantry_info["dist"]
            if dist is not None:
                dt = down_time - up_time
                dt_seconds = round(dt.total_seconds(), 2)
                dt_hours = dt_seconds / 3600
                speed = round((dist / dt_hours), 2)
                # 保存最新添加的车辆信息
                # if vlp not in last_type_pass_time_ture.keys():
                if down_time >= new_time:
                    self.type_pass_time_ture[vlp] = {"timestamp": down_time,
                                                     "vlp": vlp,
                                                     "vtype": vehicle_type,
                                                     "duration": dt.total_seconds()}
                # 保存时间区间的各种速度信息
                if vehicle_type not in type_speed_dict.keys():
                    type_speed_dict[vehicle_type] = {}
                    type_speed_dict[vehicle_type]["speed_list"] = []
                    type_speed_dict[vehicle_type]["slow_level_list"] = []
                type_speed_dict[vehicle_type]["speed_list"].append(speed)
        # 计算平均速度，慢行数量等信息
        for vehicle_type in type_speed_dict.keys():
            speed_list = type_speed_dict[vehicle_type]["speed_list"].copy()
            mean_speed = sum(speed_list) / len(speed_list)
            type_speed_dict[vehicle_type]["mean_speed"] = round(mean_speed, 2)
            type_speed_dict[vehicle_type]["count"] = len(speed_list)
            # 判断是否慢行
            for i in range(len(speed_list)):
                slow_level = 0
                if speed_list[i] < 20:
                    slow_level = 4
                elif speed_list[i] < 30:
                    slow_level = 3
                elif speed_list[i] < 40:
                    slow_level = 2
                elif speed_list[i] < 60:
                    slow_level = 1
                type_speed_dict[vehicle_type]["slow_level_list"].append(slow_level)
            # 统计慢行小客车的数量
            slow_level_list = type_speed_dict[vehicle_type]["slow_level_list"].copy()
            level_0 = slow_level_list.count(0)
            level_1 = slow_level_list.count(1)
            level_2 = slow_level_list.count(2)
            level_3 = slow_level_list.count(3)
            level_4 = slow_level_list.count(4)
            type_speed_dict[vehicle_type]["slow_level_count"] = [level_0, level_1, level_2, level_3, level_4]
        # 计算通过率
        in_vlp_dict = self.gantry_data["up_vlp_time_dict"].copy()
        for vlp in in_vlp_dict.keys():
            in_time = in_vlp_dict[vlp][self.define["TIME"]]
            in_type = in_vlp_dict[vlp][self.define["TYPE"]]
            if not flag:
                if in_type != "1":
                    continue
            if in_type not in self.type_pass_time.keys():
                in_type = "0"
            pass_time_config = self.type_pass_time[in_type]
            want_time = in_time + timedelta(minutes=pass_time_config)
            if(self.start_time - self.time_move) <= want_time < (self.end_time - self.time_move):
                if in_type not in type_pass_rate_dict.keys():
                    type_pass_rate_dict[in_type] = {}
                    type_pass_rate_dict[in_type]["count"] = 0
                    type_pass_rate_dict[in_type]["pass"] = 0
                    type_pass_rate_dict[in_type]["no_pass"] = 0
                type_pass_rate_dict[in_type]["count"] += 1
                if vlp in self.gantry_data["interval_dict"].keys():
                    type_pass_rate_dict[in_type]["no_pass"] += 1
        for in_type in type_pass_rate_dict.keys():
            type_pass_rate_dict[in_type]["pass"] = type_pass_rate_dict[in_type]["count"] - type_pass_rate_dict[in_type]["no_pass"]

            # want_time = in_time + timedelta(minutes=pass_time_config)
            # if(self.start_time - self.time_move) <= want_time < (self.end_time - self.time_move):
            #     if in_type not in type_pass_rate_dict.keys():
            #         type_pass_rate_dict[in_type] = {}
            #         type_pass_rate_dict[in_type]["count"] = 0
            #         type_pass_rate_dict[in_type]["pass"] = 0
            #     type_pass_rate_dict[in_type]["count"] += 1
            #     if vlp in self.gantry_data["down_vlp_time_dict"].keys():
            #         out_time = self.gantry_data["down_vlp_time_dict"][vlp][self.definene["TIME"]]
            #         pass_time = (out_time - in_time).total_seconds() / 60
            #         if pass_time <= pass_time_config:
            #             type_pass_rate_dict[in_type]["pass"] += 1
            # elif vlp in self.gantry_data["down_vlp_time_dict"].keys():
            #     if in_type not in type_pass_rate_dict.keys():
            #         type_pass_rate_dict[in_type] = {}
            #         type_pass_rate_dict[in_type]["count"] = 0
            #         type_pass_rate_dict[in_type]["pass"] = 0
            #     type_pass_rate_dict[in_type]["count"] += 1
            #     out_time = self.gantry_data["down_vlp_time_dict"][vlp][self.define["TIME"]]
            #     pass_time = (out_time - in_time).total_seconds() / 60
            #     if pass_time <= pass_time_config:
            #         type_pass_rate_dict[in_type]["pass"] += 1

        return type_speed_dict, type_pass_rate_dict

    def data_analysis(self, q):
        return_data = {}
        self.load_time = datetime.now()
        # 如果超过时间窗口，则移动时间窗口，并计算窗口内的各项数据
        if self.current_simulated_time is not None and self.diff_time is not None and (self.load_time + self.diff_time) >= self.end_time:
            # 计算当前时间窗口内的上下游车辆数量
            i = 0
            for t in self.gantry_data["current_up_list"]:
                if self.start_time <= t < self.end_time:
                    i += 1
            j = 0
            for t in self.gantry_data["current_down_list"]:
                if self.start_time <= t < self.end_time:
                    j += 1
            # 移动时间窗口
            self.start_time += self.time_move
            self.end_time += self.time_move
            # 将当前窗口内的数据计算并保存
            return_data["data"] = {"time": self.end_time - self.time_move,
                                   "up_flow_num": i,
                                   "down_flow_num": j,
                                   "in_num": self.gantry_data["in_num"],
                                   "out_num": self.gantry_data["out_num"],
                                   "interval_num": 0,
                                   "interval_dict": self.gantry_data["interval_dict"],
                                   "type_speed_dict": {},
                                   "type_pass_rate_dict": {}}
            self.gantry_data["in_num"] = 0
            self.gantry_data["out_num"] = 0
            return_data["info"] = self.gantry_info
            return_data["info"]["car_pass_time"] = self.type_pass_time["1"]
            return_data["info"]["time_interval"] = self.window_length
            return_data["info"]["time_move"] = self.time_move.total_seconds()/60
            type_speed_dict, type_pass_rate_dict = self.type_analysis()
            return_data["data"]["type_speed_dict"] = type_speed_dict
            return_data["data"]["type_pass_rate_dict"] = type_pass_rate_dict
            return_data["data"]["type_pass_time_ture"] = self.type_pass_time_ture
            # 计算滞留车辆（由于门架卡口相机存在漏识别、误识别，会导致滞留车辆数量持续增高，带优化后使用该数据）
            for key in self.gantry_data["interval_dict"].keys():
                end_time = self.end_time - self.time_move
                if self.gantry_data["interval_dict"][key][self.define["TIME"]] <= end_time:
                    return_data["data"]["interval_num"] += 1

            # 清除过期数据(一小时前未匹配上的上游门架数据)
            self.expire_clear(self.start_time, self.end_time)

        # 添加新数据
        self.add_message(q)

        return return_data

    def get_flag(self, flag_q):
        '''
        监控线程是否需要结束
        '''
        while not self.flag:
            while not flag_q.empty():
                flag = flag_q.get(timeout=0.1)
                if flag:
                    self.flag = True

            time.sleep(0.1)

    def run(self, q, level, kafka_data, flag_q):
        # 启动监控线程
        threading.Thread(target=self.get_flag, args=(flag_q,)).start()
        # 初始化
        last_return_data = None
        json_file = open(self.save_json_path, 'w', encoding='utf-8')
        while not self.flag:
            time.sleep(0.01)
            content = None
            con = None
            return_data = self.data_analysis(q)
            if last_return_data is None and return_data:
                last_return_data = return_data
            if return_data and last_return_data:
                if return_data != last_return_data:
                    # print("数据更新", self.gantry_info["up_gantry_id"], return_data["data"]["time"])
                    # 计算事故
                    data = return_data
                    last_data = last_return_data
                    content, content_info = self.monitor.run(data, last_data)
                    last_return_data = return_data
                    con = self.congestion.run(return_data)
                    # 后续均为数据处理操作，主要是拼接字段信息到各自队列以用于上报kafka
                    # 获取新的小客车通行时间duration_info
                    duration_info = []
                    for vlp, vlp_data in self.type_pass_time_ture.items():
                        duration_info.append({"timestamp": vlp_data["timestamp"].strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3],
                                              "vtype": vlp_data["vtype"],
                                              "vlp": vlp_data["vlp"],
                                              "carDuration": vlp_data["duration"]})
                    # 计算时间区间内的通过车辆数量和平均速度
                    pass_num = 0
                    for k, v in return_data["data"]["type_speed_dict"].items():
                        pass_num += len(v["speed_list"])
                    if "1" in return_data["data"]["type_speed_dict"]:
                        car_mean_speed = return_data["data"]["type_speed_dict"]["1"]["mean_speed"]
                    else:
                        car_mean_speed = 0
                    data = {"time": self.current_simulated_time, "con": con, "content": content, "num": pass_num, "speed": car_mean_speed}
                    # 如果阻断，上报阻断信息到队列
                    if content != "畅通" or con != "畅通":
                        level.put(data, block=False)
                    # 将最新的监测信息等数据放到队列中
                    # 计算事件等级1～5
                    level_dict = {"畅通": 0, "轻度拥堵": 1, "中度拥堵": 2, "严重拥堵": 3, "阻断": 4, "拥堵+阻断": 5}
                    if content == "畅通" and con == "畅通":
                        event_level = 0
                    elif content == "畅通" and con != "畅通":
                        event_level = level_dict[con]
                    elif content != "畅通" and con == "畅通":
                        event_level = 4
                    else:
                        event_level = 5
                    kafka_data_dict = {
                        "timestamp": return_data["data"]["time"].strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3],
                        "sn": self.gantry_info["down_gantry_id"],
                        "congestionFlag": con,
                        "eventFlag": content,
                        "abnormalFlag": "正常",
                        "flowInfo": {
                            "upFlow": return_data["data"]["up_flow_num"],
                            "downFlow": return_data["data"]["down_flow_num"]
                        },
                        "durationInfo": duration_info,
                        "passRateInfo": content_info["current_pass_rate"],
                        "eventLevel": event_level,
                        "in_num": return_data["data"]["in_num"],
                        "out_num": return_data["data"]["out_num"]
                    }
                    kafka_data.put(kafka_data_dict, block=False)
                    # 保存过程数据到本地json中
                    if self.SAVE:
                        save_data = kafka_data_dict.copy()
                        car_num = 0
                        car_speed = 0
                        car_pass = 100
                        car_slow_num = 0
                        car_pass_time = 0
                        if "1" in return_data["data"]["type_speed_dict"]:
                            car_num = return_data["data"]["type_speed_dict"]["1"]["count"]
                            car_speed = return_data["data"]["type_speed_dict"]["1"]["mean_speed"]
                            num = return_data["data"]["type_speed_dict"]["1"]["slow_level_count"]
                            car_slow_num = num[1] + num[2] + num[3]
                            car_pass_time = self.gantry_info["dist"] / car_speed * 3600
                            car_pass_time = round(car_pass_time, 2)
                        if "1" in return_data["data"]["type_pass_rate_dict"]:
                            car_pass = return_data["data"]["type_pass_rate_dict"]["1"]["pass"] / \
                                       return_data["data"]["type_pass_rate_dict"]["1"]["count"] * 100
                            car_pass = round(car_pass, 2)
                        pass_rate_dict = {"pass_num": 0, "all_count": 0}
                        for vtype in return_data["data"]["type_pass_rate_dict"].keys():
                            car_pass_rate = return_data["data"]["type_pass_rate_dict"][vtype]
                            pass_rate_dict["pass_num"] += car_pass_rate["pass"]
                            pass_rate_dict["all_count"] += car_pass_rate["count"]
                        all_pass_rate = int(pass_rate_dict["pass_num"] / pass_rate_dict["all_count"] * 100) if pass_rate_dict["all_count"] != 0 else 100
                        new_row = {
                            "time": return_data["data"]["time"].strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3],
                            "upFlowNum": return_data["data"]["up_flow_num"],
                            "downFlowNum": return_data["data"]["down_flow_num"],
                            "carPass": car_pass,
                            "carNum": car_num,
                            "carSpeed": car_speed,
                            "allNum": pass_rate_dict["all_count"],
                            "allPass": all_pass_rate,
                            "carSlowNum": car_slow_num,
                            "carPassTime": car_pass_time,
                            "flowFlag": content_info["flow_change_flag"],
                            "flowDiff": content_info["flow_diff"],
                            "flowDiffP": content_info["flow_diff_p"],
                            "speedFlag": content_info["speed_change_flag"],
                            "speedDiff": content_info["speed_60_diff"],
                            "flowEmpty": content_info["flow_empty_flag"],
                            "passFlag": content_info["pass_flag"],
                            "intervalDiff": content_info["interval_diff"],
                            "durationNum": content_info["duration_num"],
                            "duration_average": content_info["duration_average"],
                            "durationValue": content_info["duration_value"],
                            "oneFrameNum": content_info["one_frame_num"],
                            "block_flag": content_info["block_flag"],
                            "score": content_info["block_probability"],
                            "con": con,
                            "eventFlag": content,
                        }
                        new_row_1 = [
                            return_data["data"]["time"].strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3],
                            return_data["data"]["up_flow_num"],
                            return_data["data"]["down_flow_num"],
                            car_pass,
                            car_num,
                            car_speed,
                            pass_rate_dict["all_count"],
                            all_pass_rate,
                            car_slow_num,
                            car_pass_time,
                            content_info["flow_change_flag"],
                            content_info["flow_diff"],
                            content_info["flow_diff_p"],
                            content_info["speed_change_flag"],
                            content_info["speed_60_diff"],
                            content_info["flow_empty_flag"],
                            content_info["pass_flag"],
                            content_info["interval_diff"],
                            content_info["duration_num"],
                            content_info["duration_average"],
                            content_info["duration_value"],
                            content_info["one_frame_num"],
                            content_info["block_flag"],
                            content_info["block_probability"],
                            con,
                            content
                        ]
                        save_data["new_row_1"] = new_row_1
                        json_str = json.dumps(save_data, ensure_ascii=False)
                        json_file.write(json_str + '\n')

        json_file.close()

